package byx.container.annotation.extension.impl;

import byx.container.annotation.extension.core.ClassProcessorContext;
import byx.container.core.utils.CastUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.util.List;

/**
 * 条件注入处理器基类
 */
public abstract class ConditionalRegisterProcessor extends BaseClassProcessor {
    private final List<ConditionalAnnotationHandler<?>> handlers;

    protected ConditionalRegisterProcessor(ClassScanner classScanner, List<ConditionalAnnotationHandler<?>> handlers) {
        super(classScanner);
        this.handlers = handlers;
    }

    // 查找可用的ConditionalAnnotationHandler
    protected ConditionalAnnotationHandler<?> findConditionalAnnotationHandler(AnnotatedElement element) {
        for (ConditionalAnnotationHandler<?> h : handlers) {
            if (element.isAnnotationPresent(h.getAnnotationType())) {
                return h;
            }
        }
        return null;
    }

    // 判断是否需要注入
    protected boolean needToRegister(AnnotatedElement element, ConditionalAnnotationHandler<?> handler, ClassProcessorContext ctx) {
        Annotation annotation = element.getAnnotation(handler.getAnnotationType());
        return handler.needToRegister(CastUtils.cast(annotation), ctx.getContainer());
    }
}
